<template>
    <div>
    <el-dialog :title=" $t('basItemRoute.import')" v-model="visible" height = "2000" width="1500" :close-on-click-modal="false" draggable >
        
         <!--查询表单-->
         <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">

            <el-form-item :label="$t('basItemRoute.excelFile')" prop="excelFile">
                <el-input v-model="state.queryForm.excelFile" style="width: 500px" clearable disabled
                    :placeholder="$t('basItemRoute.selectExcelFile')" >
                    <template #append>
                        <el-upload
                            ref="uploadRef"
                            class="upload-demo"
                            :headers="headers"
                            action='/api/wms/po/CompleteImportPoShipDetai'
                            name ="excelFile"
                            :show-file-list="false"
                            :on-success="handleSuccess"
                            :on-error="handleError" >
                            <template #trigger>
                            <el-button type="primary">{{ $t('basItemRoute.select') }}<el-icon><Select /></el-icon></el-button>
                            </template>
                        </el-upload>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item>
                <!-- <el-button icon="documentAdd" type="success" @click="getDataList">
                    {{ $t('basItemRoute.import') }}
                </el-button> -->
                <el-button icon="download" type="success" plain @click="exportTemplate">
                    {{ $t('basItemRoute.downloadTemplate') }}
                </el-button>
            </el-form-item>
         </el-form>
                     <!--查询结果的列表-->
                     <el-table :data="state.dataList" highlight-current-row v-loading="state.loading" border
                        style="width: 100%;height: 100%" :cell-style="tableStyle.cellStyle" stripe
                        :header-cell-style="tableStyle.headerCellStyle">
                        <el-table-column type="selection" width="40" align="center" />
					<el-table-column type="index" label="#" width="50" />
                    <el-table-column prop="isAdd" :label="$t('operation.isAdd')" width="180" show-overflow-tooltip>
						<template #default="scope">
							<el-tag :type="scope.row.isAdd ? 'warning' : 'primary'" effect="dark">{{ scope.row.isAdd ? $t('qms.yes') : $t('qms.no') }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="poCode" :label="$t('bar.poCode')" width="180" show-overflow-tooltip>
						<template #default="scope">
							<el-tag :type="scope.row.isAbroad ? 'warning' : 'primary'" effect="light">{{ scope.row.poCode }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="poLine" width="120" :label="$t('bar.poLine')" show-overflow-tooltip />
                    <el-table-column prop="estimatedArrivalDate"  width="160" :label="$t('upgrade.ArrivalDate')">
						<template #default="scope">
							{{ scope.row.estimatedArrivalDate }}
						</template>
					</el-table-column>
                    <el-table-column prop="requiredQty" width="160" :label="$t('dailyDeliveryData.salesQty')">
						<template #default="scope">
							<el-tag type="success" effect="light">
								{{ scope.row.requiredQty }}
							</el-tag>
						</template>
					</el-table-column>
                    <el-table-column prop="shippingQty" width="160" :label="$t('upgrade.shipment')" show-overflow-tooltip >
                        <template #default="scope">
							<el-tag type="success" effect="dark">
								{{ scope.row.shippingQty }}
							</el-tag>
						</template>
                    </el-table-column>
					<el-table-column prop="shippingDate" width="160" :label="$t('upgrade.shipmentDate')" >
						<template #default="scope">
							{{ scope.row.shippingDate }}
						</template>
					</el-table-column>  
					<el-table-column prop="supplierName" width="250" :label="$t('poheader.supplierName')" show-overflow-tooltip />
					<el-table-column prop="purDate" width="160" :label="$t('poheader.purDate')" show-overflow-tooltip >
						<template #default="scope">
							{{ scope.row.purDate }}
						</template>
					</el-table-column>
					<el-table-column prop="materialCode" width="160" :label="$t('agv.materialCode')">
						<template #default="scope">
							<el-tag type="primary" effect="light">{{ scope.row.materialCode }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="materialName" width="200" :label="$t('agv.materialName')"  show-overflow-tooltip>
						<template #default="scope">
							{{ scope.row.materialName }}
						</template>
					</el-table-column>
					<el-table-column prop="unit"  width="100" :label="$t('bom.unit')" />
					<el-table-column prop="spec" width="180" :label="$t('basMaterial.specification')">
						<template #default="scope">
							<el-tag type="success" effect="light">
								{{ scope.row.spec == ' ' ? '--' : scope.row.spec }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="requiredDate" width="160" :label="$t('so.deliverydate')" show-overflow-tooltip >
						<template #default="scope">
							{{ scope.row.requiredDate }}
						</template>
					</el-table-column>
                    <el-table-column prop="id" width="80" label="Id" show-overflow-tooltip />
                    </el-table>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="visible = false" icon="Close">{{$t('basItemRoute.cancel')}}</el-button>
                            <el-button type="primary" @click="onSubmit" :disabled="loading" icon="Check">{{$t('basItemRoute.confirm')}}</el-button>
                        </span>
                    </template>
    </el-dialog>
</div>
</template>

<script setup lang="ts">
import {useI18n} from "vue-i18n";
import {BasicTableProps, useTable} from "/@/hooks/table";
import {useMessage, useMessageBox} from "/@/hooks/message";
import ExcelJS from 'exceljs';
import { saveImportPoShipDetai } from '/@/api/platform/mes/wmsCheckstock';
import {Session} from '/@/utils/storage';

const { t } = useI18n();

// 定义变量内容
const loading = ref(false);
const visible = ref(false);
const emits = defineEmits(['getChildren'])
const dataForm = reactive({
    excelFile: '',
})
/**
 * 计算请求头部信息
 */
const headers = computed(() => {
  return {
    Authorization: 'Bearer ' + Session.getToken(),
    'TENANT-ID': Session.getTenant(),
  };
});

//上传成功事件
const handleSuccess = (data:any,uploadFile: any) => {
    if(data.msg != "null"){
        useMessage().error(data.msg);
    }else{
        console.log("上传成功", data);
        state.queryForm.excelFile = uploadFile.name
        state.dataList = data.data
    }
}
const handleError = (error:any) => { }

const formatDate = (date) => {
	if (!date) return '';
	const d = new Date(date);
	const year = d.getFullYear();
	const month = String(d.getMonth() + 1).padStart(2, '0');
	const day = String(d.getDate()).padStart(2, '0');
	return `${year}-${month}-${day}`;
};
//导出模板
const exportTemplate = () => {
    // 创建工作簿对象
    const workbook = new ExcelJS.Workbook();

    // 创建工作表对象
    const worksheet = workbook.addWorksheet('Sheet1');

    // 添加表头行
    worksheet.addRow(['ID', '采购订单号', '采购订单行', '预计到达日期', '本次发货时间', '本次发货数量',]);
    worksheet.addRow(['', 'CGDD0000000001', '1', '2025/03/31', '2025/02/15', '10086','模板数据，用时请删除此行！']);

    // 保存Excel文件
    workbook.xlsx.writeBuffer().then(buffer => {
        // 创建Blob对象
        const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

        // 创建下载链接
        const url = URL.createObjectURL(blob);

        // 创建下载元素并触发下载
        const link = document.createElement('a');
        link.href = url;
        link.download = '采购订单发货模板.xlsx';
        link.click();

        // 释放URL对象
        URL.revokeObjectURL(url);
    });
}

//查询
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: ""
})


// 提交
const onSubmit = async () => {
    if (state.dataList?.length === 0) {
        useMessage().error(t('basItemRoute.importDataIsNull'));
        return false;
    }
    callInterface()
};

const callInterface = async () => {
    try {
        loading.value = true;
        await saveImportPoShipDetai(state.dataList);
        useMessage().success(t('basItemRoute.importSuccess'));
        visible.value = false;
        emits('getChildren', loading);
    } catch (err: any) {
        useMessage().error(err.msg);
    } finally {
        loading.value = false;
    }
}

// 打开弹框
const openAddDialog = () => {
    visible.value = true;
    // 重置表单数据
    nextTick(() => {
        state.queryForm.excelFile = null;
        state.dataList = [];
    });

};

// 定义表单校验规则
const dataRules = reactive({
    excelFile: [
        { required: true, message: t('basItemRoute.selectExcelFile'), trigger: 'blur' },
    ]
})

const {
    getDataList,
    currentChangeHandle,
    sizeChangeHandle,
    sortChangeHandle,
    downBlobFile,
    tableStyle
} = useTable(state)

// 暴露变量
defineExpose({
    openAddDialog
});
</script>